package com.reservationserver.config;

import com.reservationpojo.utils.Jwtutils;
import com.reservationserver.service.admin.Mgrservice;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /*
    controller执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        // 从http请求头中取出token
        log.info("输出token" + request.getHeader("token"));
        String token = request.getHeader("token");
        String id,flag;
        try {
            Claims claims = Jwtutils.parseJwt(token);
            id = claims.getId();
            flag = redisTemplate.opsForValue().get(id);
        } catch (Exception e) {
            log.info("解析失败");
            return false;
        }

        if (flag == null) {
            log.info("未有数据");
            return false;
        }


        log.info("获取token，放行");
        return true;
    }

}

